import React, {Component} from 'react'
import {View, Text, StyleSheet, Image, Alert, TouchableHighlight, TouchableOpacity, Button} from 'react-native'
import HeadingLine from '../common/heading_line'
import {STUDENT} from '../../config/enumeration'
import {PostAnswerApi, PutRetractAnswerApi, PostTeacherReplyApi, PutRetractReplyApi} from '../../config/api'
import NavigatorService from '../../config/navigate_service'
import {update_homework, refresh_homeworks} from '../../redux/actions/homework'
import {fetch_correct_classrooms} from '../../redux/actions/correcting_classroom'
import {connect} from 'react-redux'
import AnswerOperate from '../answers/answer_operate'
import AnswerDetail from '../answers/answer_detail'
import ReplyDetail from '../answers/reply_detail'
import ReplyOperate from '../answers/reply_operate'
import styles from '../../config/styles'

//学生提交作业和显示作业的组件
class StudentHomework extends Component {
    static defaultProps = {
        answer: {},
        role: 1,
        homework_id: 1, 
        isLastReply: false,
        isLastAnswer: false
    }

    constructor(props) {
        super(props)
        this.state = {
            content: '',
            score: 0,
            attachments: [],
            answer: props.answer,
            submitting: false,
            homework_status: props.homework_status,
            isLastReply: props.isLastReply,
            isLastAnswer: props.isLastAnswer
        }
    }

    //点击角标删除attachment的事件
    onRemoveAttachment = (attachment_name) => {
        Alert.alert('删除提醒', '确认要删除这个附件吗？',[
                {text: '取消', onPress: () => {}},
                {text: '确定', onPress: () => {
                    let _attachments = this.state.attachments.filter((atta, index) => {
                        return atta.name != attachment_name
                    })
                    this.setState({attachments: _attachments})
                }}
            ]
        )
    }


    //是否有回答
    hasNotAnswered = () => {
        return this.state.answer.answer_at == ""
    }

    //是否可以批改
    canReply = () => {
        const answer = this.state.answer
        return answer.reply && answer.reply.replied_at == null && ['revised', 'answered', 'finished'].includes(this.state.homework_status)
    }

    //提交作业
    submitAnswer = () => {
        if (this.state.submitting == true) return
        this.setState({submitting: true})
        PostAnswerApi({
            id: this.state.answer.id,
            content: this.state.content,
            attachments: this.state.attachments
        }).then((data) => {
            if (data.code == 0) {
                Toast.show('提交成功')
                // let _answer = this.state.answer;
                // _answer.answer_at = "刚刚"
                // _answer.content = this.state.content
                // this.state.attachments.forEach((atta) => {atta.allowDestroy = false})
                // _answer.attachments = this.state.attachments
                // this.setState({
                //     answer: _answer,
                //     submitting: false
                // })
                NavigatorService.back()
                //通知homework的这条homework,状态更新
                this.props.dispatch(update_homework(this.props.homework_id, {status: 'answered'}))
                //NavigatorService.back()
            }
        })
    }

    //撤回作业
    retractAnswer = () => {
        if (this.state.submitting == true) return        
        this.setState({submitting: true})
        PutRetractAnswerApi(this.state.answer.id, this.props.homework_id, 2).then((data) => {
            console.log('data', data)
            if (data.code == 0) {
                Toast.show('撤回成功')
                NavigatorService.back()
                // let _answer = this.state.answer
                // _answer.answer_at = ""
                // this.state.attachments.forEach((atta) => {atta.allowDestroy = true})
                // _answer.attachments = this.state.attachments
                // this.setState({
                //     answer: _answer,
                //     submitting: false
                // })
                //通知homework的这条homework,状态更新
                this.props.dispatch(update_homework(this.props.homework_id, {status: 'init'}))    
            }
        })        
    }

    //撤回批改
    retractReply = () => {
        if (this.state.submitting == true) return
        if (this.state.answer.reply == null) return
        this.setState({submitting: true})
        PutRetractReplyApi(this.state.answer.reply.id).then((data) => {
            if (data.code === 0) {
                // this.props.dispatch(refresh_homeworks())                
                this.props.dispatch(fetch_correct_classrooms(this.props.homework_id))
                NavigatorService.back()
                // let _reply = this.state.answer.reply
                // let _answer = this.state.answer
                // _reply.replied_at = null
                // this.state.attachments.forEach((atta) => {atta.allowDestroy = true})   
                // _reply.attachments = this.state.attachments
                // _answer.reply = _reply
                // this.setState({submitting: false, answer: _answer})    
            }
        })
    }

    //批改作业
    correctReply = (isFinish) => {
        if (this.state.submitting == true) return
        this.setState({submitting: true}) 
        PostTeacherReplyApi({
            isFinish: isFinish,
            score: this.state.score,
            content: this.state.content,
            attachments: this.state.attachments,
            id: this.state.answer.reply.id
        }).then((data) => {
            if (data.code === 0) {
                // this.props.dispatch(refresh_homeworks())                                
                this.props.dispatch(fetch_correct_classrooms(this.props.homework_id)) 
                NavigatorService.back()
                // let _reply = this.state.answer.reply
                // _reply.replied_at = '刚刚'
                // _reply.score = this.state.score
                // _reply.content = this.state.content
                // this.state.attachments.forEach((atta) => {atta.allowDestroy = false})
                // _reply.attachments = this.state.attachments
                // this.setState({submitting: false})                
            }
        })
    }

    //附件完成上传之后
    onFinishedUpload = (name, type, awsPath) => {
        let _onDestroy = () => {this.onRemoveAttachment(name)}
        let new_attachment = {
            type: type,
            url: awsPath,
            name: name,
            allowDestroy: true,
            onDestroy: _onDestroy
        }
        this.state.attachments.push(new_attachment)
        this.setState({
            attachments: this.state.attachments
        })
    }

    //改变content
    onChangeContent = (new_content) => {
        this.setState({content: new_content})
    }

    teacher_foot_component = () => {
        const answer = this.state.answer
        if (this.canReply()) {
            return(
                <View style={{flexDirection: 'row', marginTop: 10, padding: 10}}>
                    <View style={{alignItems: 'center', justifyContent: 'center', flex: 1}}>
                        <TouchableOpacity style={[styles.as_button, styles.background_orange]} onPress={() => {this.correctReply(false)}}>
                            <Text style={{color: 'white'}}>{this.state.submitting ? '提交中...' : ' 订正 '}</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
                        <TouchableOpacity style={[styles.as_button, styles.background_blue]} onPress={() => {this.correctReply(true)}}>
                            <Text style={{color: 'white'}}>{this.state.submitting ? '提交中...' : ' 完成 '}</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            )
        } else if (answer.reply && answer.reply.score != null && this.state.isLastAnswer ) {
            return (
                <View style={{padding: 20}}>
                    <Button title={this.state.submitting ? '提交中...' : ' 撤回 '} onPress={() => {this.retractReply()}} color={'#ff951a'}/>
                </View>
            )
        } else {
            return null
        }
    }    

    student_foot_component = () => {
        //answer_at为空代表没提交
        if (this.hasNotAnswered()) {
            return (
                <TouchableOpacity
                    disabled={this.state.submitting} 
                    onPress={this.submitAnswer} 
                    style={styles.answer_button} 
                >
                    <View>
                        <Text style={{color: '#33CCFF'}}>
                            {this.state.submitting ? '提交中...' : '提交作业'}
                        </Text>
                    </View>
                </TouchableOpacity>
            )
            //reply.reply_at为空代表没批改
        } else  {
            return(
                <TouchableOpacity
                    disabled={this.state.submitting}
                    style={styles.answer_button} 
                    onPress={this.retractAnswer}
                >
                    <View>
                        <Text style={{color: '#FF8800'}}>
                            {this.state.submitting ? '提交中...' : '撤回'}
                        </Text>
                    </View>
                </TouchableOpacity>
            )
            
        }
    }

    /*
    老师和学生的逻辑不太一样，对于老师，无论这个answer的批改有没有分数，都要显示一条批改，
    但是没有分数的可以跳转至批改页面.
    对于学生，如果没有批改分数，则不显示批改栏
    */
    render () {
        const role = this.props.role
        const answer = this.state.answer
        if (role == STUDENT) {
            return (
                <View style={{paddingTop: 10}}>
                    {(answer.reply && answer.reply.score) == null ? 
                        null : 
                        <HeadingLine 
                            title='老师批改'
                            color={'#ff951a'}
                            header_right={() => {return(<Text>评分：{answer.reply.score}</Text>)}}
                            style={{backgroundColor: 'white'}}
                            contentStyle ={{backgroundColor: 'white'}}
                        >
                            <ReplyDetail reply={answer.reply}/>
                        </HeadingLine>
                    }
                    <HeadingLine 
                        title='学生作业' 
                        color={'#00DB00'} 
                        style={{backgroundColor: 'white', paddingTop: 10}}
                        contentStyle ={{backgroundColor: 'white'}}                        
                        foot_component={this.student_foot_component}
                        collapsible={!this.hasNotAnswered()}
                    >
                        {
                            this.hasNotAnswered() ?
                                <AnswerOperate
                                    onFinishedUpload={this.onFinishedUpload}
                                    onChangeContent={this.onChangeContent}
                                    attachments={this.state.attachments}
                                    content={this.state.content}
                                /> :
                                <AnswerDetail answer={answer} />            
                        }
                    </HeadingLine>
                </View>
            )
        } else {
            if (this.hasNotAnswered()) {
                return null
            } else {
                return (
                    <View style={{paddingTop: 10}}>
                        <HeadingLine 
                            title='学生作业' 
                            color={'#00DB00'} 
                            style={{backgroundColor: 'white', paddingTop: 10}}
                            contentStyle ={{backgroundColor: 'white'}}                        
                            collapsible={!this.hasNotAnswered()}
                        >
                            <AnswerDetail answer={answer} />            
                        </HeadingLine>
                        <HeadingLine 
                            title='老师批改'
                            color={'#ff951a'}
                            header_right={() => {
                                return(answer.reply.score == null ? <Text>未批</Text> : <Text>评分：{answer.reply.score}</Text>)                                                     
                            }}
                            style={{backgroundColor: 'white', marginTop: 10}}
                            contentStyle ={{backgroundColor: 'white'}}
                            collapsible={!this.canReply()}
                            foot_component={this.teacher_foot_component}                     
                        >
                            {
                                this.canReply() ?
                                    <ReplyOperate
                                        onFinishedUpload={this.onFinishedUpload}
                                        onChangeContent={this.onChangeContent}
                                        attachments={this.state.attachments}
                                        content={this.state.content}
                                        onScoreChange={(score) => this.setState({score: score})}
                                        score={this.state.score}
                                    /> : 
                                    <ReplyDetail reply={answer.reply}/>                                
                            }
                        </HeadingLine>
                    </View>      
                )
            }    
        }
    }
}


const mapStateToProps = (state) => {
    return {
        homework: state.homework,
        correcting_classroom: state.correcting_classroom
    }
}

export default connect(mapStateToProps)(StudentHomework)
